package com.yzt.insys.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.session.Session;

import com.yzt.insys.beans.Role;
import com.yzt.insys.beans.User;
import com.yzt.insys.common.Constants;
import com.yzt.insys.dto.UserDto;

public class UserUtil {
	
	
	/**
	 * 
	 * @param session shiro中的session
	 * @param user
	 */
	public static void saveUserToSession(Session session,User user){
		session.setTimeout(-1);//设置session记不过期
		session.setAttribute(Constants.USER_KEY_IN_SESSION,user);
	}
	
	/**
	 * 
	 * @param session HttpSession
	 * @param user
	 */
	public static void saveUserToSession(HttpSession session,User user){
		session.setAttribute(Constants.USER_KEY_IN_SESSION,user);
	}
	
	
	/**
	 * 将user保存在cookie中,cookie的过期时间为1年
	 * @param response
	 * @param user
	 */
	public static void saveUserToCookie(HttpServletResponse response,User user){
		Cookie userNameCookie=new Cookie("userName",user.getUserName());
		Cookie userPwdCookie=new Cookie("userPwd",user.getUserPwd());
		userNameCookie.setMaxAge(1*365*24*60*60);
		userPwdCookie.setMaxAge(1*365*24*60*60);
		response.addCookie(userNameCookie);
		response.addCookie(userPwdCookie);
	}
	/**
	 * 从HttpSession获取当前用户信息
	 * @param session
	 * @return
	 */
	public static UserDto getUserFromSession(HttpSession session) {
		Object attribute = session.getAttribute(Constants.USER_KEY_IN_SESSION);
		return attribute == null ? null : (UserDto) attribute;
	}
	
	/**
	 * 从Session(shiro)获取当前用户信息
	 * @param session
	 * @return
	 */
	public static UserDto getUserFromSession(Session session) {
		Object attribute = session.getAttribute(Constants.USER_KEY_IN_SESSION);
		return attribute == null ? null : (UserDto) attribute;
	}
	
	/**
	 * 获取角色的所有id
	 * @param roles
	 * @return返回角色的id集合
	 */
	public static List<Long> getRoleIds(List<Role> roles){
		List<Long> roleIds=null; 
		if(roles!=null&&roles.size()>0){
			roleIds=new ArrayList<Long>();
			for(Role role:roles){
				roleIds.add(role.getId());				
			}
		}
		return roleIds;
	}
}
